package groovy

/**
 * 集合测试:
 * 参考资料：https://www.ibm.com/developerworks/cn/education/java/j-groovy/j-groovy.html
 *
 * @author : zenghua
 * @version : v0.1 CollectionTest.java
 * @since : 2017/9/13 18:13
 */
class CollectionTest {

    public static void main(String[] args) {

//        validateCollection();
//        operate();
//        map();
        ite();
    }



    def static validateCollection() {
        def range = 0..4
        println range.class
        println(range instanceof List)
        assert range instanceof List
    }

    def static operate() {
        def list = ["tom", "jerry", "tiger"]
        list.add("snake");
        //相当于add
        list << "monkey";
        list[5] = "cat";
        println(list.size());
        assert  list instanceof Collection;
        assert list instanceof ArrayList;



        //集合加减
        def numbers = [1,2,3,4]
        assert numbers + 5 == [1,2,3,4,5]
        assert numbers - [2,3] == [1,4]
    }

    /**
     * map测试
     * @return
     */
    def static map() {
        def map = [name:"hello", "win": 12];
        //默认为LinkedHashMap
        assert map instanceof LinkedHashMap;
        map.put("foo", 2);
        println(map.get("foo"));
        println(map.name);
        println(map["win"]);


    }

    /**
     * 集合遍历测试
     */
    def static ite() {
        def list = ["tom", "jerry", "tiger"];
        def map = [name:"hello", "win": 12];

        //闭包遍历list
        list.each {
            println("list元素：" + it);
        }

        //it为闭包中的关键默认遍历，可以替换
        list.each { e ->
            println("新的变量e：" + e);
        }

        map.each {
            println("key: " + it.key + ", value: " + it.value);
        }

        //key,value为关键字
        map.each{ key, value ->
            println "${key} : ${value}"
        }
    }
}
